package com.bjlytr.license.client.info;

import com.alibaba.fastjson.JSON;
import com.bjlytr.license.client.entity.LicenseCheckModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;

/**
 * @author Ledison
 * @date 2021/9/16
 */

@Data
@Slf4j
public abstract class AbstractServerInfos {

    /**
     * 组装需要额外校验的License参数
     *
     * @param isFirst
     */
    public LicenseCheckModel getServerInfos(boolean isFirst) {
        LicenseCheckModel result = new LicenseCheckModel();

        try {
            List<String> ipAddress = this.getIpAddress();
            result.setIpAddress(ipAddress);
            List<String> macAddress = this.getMacAddress();
            result.setMacAddress(macAddress);
//            result.setCpuSerial(this.getCPUSerial());
//            result.setMainBoardSerial(this.getMainBoardSerial());
            if (isFirst) {
                log.info("【服务器IP】" + ipAddress);
                log.info("【服务器mac】" + macAddress);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("获取服务器硬件信息失败" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取IP地址
     */
    protected abstract List<String> getIpAddress() throws Exception;

    /**
     * 获取Mac地址
     */
    protected abstract List<String> getMacAddress() throws Exception;

    /**
     * 获取CPU序列号
     */
    protected abstract String getCPUSerial() throws Exception;

    /**
     * 获取主板序列号
     */
    protected abstract String getMainBoardSerial() throws Exception;

    /**
     * 获取某个网络接口的Mac地址
     */
    protected String getMacByInetAddress(InetAddress inetAddr) {
        try {
            byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress();
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    stringBuffer.append("-");
                }
                //将十六进制byte转化为字符串
                String temp = Integer.toHexString(mac[i] & 0xff);
                if (temp.length() == 1) {
                    stringBuffer.append("0" + temp);
                } else {
                    stringBuffer.append(temp);
                }
            }
            return stringBuffer.toString().toUpperCase();
        } catch (SocketException e) {
            System.err.println(String.format("net: %s", JSON.toJSONString(inetAddr)));
            System.err.println("获取网络接口的Mac地址" + e.getMessage());
        }
        return null;
    }

    /**
     * 获取当前服务器所有符合条件的InetAddress
     */
    protected List<InetAddress> getLocalAllInetAddress() throws Exception {
        List<InetAddress> result = new ArrayList<>(4);
        // 遍历所有的网络接口
        for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
            NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement();
            // 在所有的接口下再遍历IP
            for (Enumeration inetAddresses = iface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
                InetAddress inetAddr = (InetAddress) inetAddresses.nextElement();
                //排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址
                /*&& !inetAddr.isSiteLocalAddress()*/
                if (!inetAddr.isLoopbackAddress()
                        && !inetAddr.isLinkLocalAddress()
                        && !inetAddr.isMulticastAddress()) {
                    result.add(inetAddr);
                }
            }
        }
        return result;
    }


    public static HashSet<String> getPhysicalAddress(String text) throws IOException {
        Process p = null;
        // 物理网卡列表
        HashSet<String> address = new HashSet<String>();

        // 执行ipconfig /all命令
        p = new ProcessBuilder("ipconfig", "/all").start();

        // 读取进程输出值
        InputStream in = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String temp = null;
        while ((temp = br.readLine()) != null) {
            System.out.println(temp);
            int idx = temp.indexOf(text);
            if (idx > 0) {
                address.add(temp.substring(text.length() + 4, temp.length()));
            }
        }

        return address;
    }

    public static void main(String[] args) {
        String[] texts = new String[]{"Physical Address. . . . . . . . . :", "物理地址. . . . . . . . . . . . . :"};
        HashSet<String> address;
        try {
            address = getPhysicalAddress(texts[0]);
            if (address == null || address.size() == 0) {
                address = getPhysicalAddress(texts[1]);
            }
            System.out.println("物理地址列表：");
            for (String add : address) {
                System.out.println(add);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

